package com.itheima.security;

import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Component
public class MyUserDetailService implements UserDetailsService {

    @Resource
    private PasswordEncoder passwordEncoder;

    private Map<String,Map<String,String>> userMap = new HashMap<>();

    private boolean inited;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //select username,password from user where username = #{username}
        initUser();
        Map<String,String> userInfo = userMap.get(username);
        if(userInfo != null){
            return new User(username,userInfo.get("pwd"),AuthorityUtils.commaSeparatedStringToAuthorityList(userInfo.get("auth")));
        }
        return new User(username,null,null);
    }

    private void initUser(){
        if(inited == false){
            //构建用户信息同时还有用户对应的权限
            Map<String,String> aaaUser = new HashMap<>();
            aaaUser.put("pwd",passwordEncoder.encode("aaa"));
            aaaUser.put("auth","ROLE_aaa,ROLE_bbb");
            userMap.put("aaa",aaaUser);

            Map<String,String> bbbUser = new HashMap<>();
            bbbUser.put("pwd",passwordEncoder.encode("bbb"));
            bbbUser.put("auth","ROLE_bbb");
            userMap.put("bbb",bbbUser);
            inited = true;
        }
    }


}
